import { createWebHashHistory, createRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

const routes = [
  { path: '/', redirect: '/home' },
  { 
    path: '/main', 
    component: () => import('@/pages/index.vue'),
    redirect: '/home',  // 添加默认重定向到/home子路由
    children: [
      { path: '/home', component: () => import('@/pages/home.vue') },
      { path: '/about', component: () => import('@/pages/about.vue') },
      { path: '/users', component: () => import('@/pages/users.vue') },
      { path: '/roles', component: () => import('@/pages/roles.vue') },
      { path: '/permissions', component: () => import('@/pages/permissions.vue') },
      // 404页面 - 匹配所有未定义的路径，放在子路由最后
      { path: '/:catchAll(.*)', component: ()=> import('@/pages/404.vue')},
    ]
  },
  { path: '/login', component: () => import('@/pages/login.vue') },
  // 404 页面
  { path: '/:catchAll(.*)', component: ()=> import('@/pages/404.vue')},
]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
})

// 全局前置守卫，用于检查用户登录状态
router.beforeEach((to, from, next) => {
  // 获取认证状态
  const authStore = useAuthStore()
  authStore.checkAuthStatus()
  
  // 如果访问的不是登录页面且用户未登录，则重定向到登录页面
  if (to.path !== '/login' && !authStore.isAuthenticated) {
    next('/login')
  } else {
    next()
  }
})

export default router